package com.situ.cloud.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.situ.cloud.common.exception.BusinessException;
import com.situ.cloud.common.vo.RS;
import com.situ.cloud.user.entity.Role;
import com.situ.cloud.user.mapper.RoleMapper;
import com.situ.cloud.user.service.IRoleService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author kkkkkk
 * @since 2023-10-24
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Override
    public RS selectRoleList(String keyword, Integer currentPage, Integer pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Role::getName, keyword);
        List<Role> list = baseMapper.selectList(wrapper);
        RS rs = RS.ok(list);
        rs.setCount(new PageInfo<>(list).getTotal());
        return rs;
    }

    @Override
    public void doSave(Role role) {
        Role r = baseMapper.selectOne(new LambdaQueryWrapper<Role>().eq(Role::getCode, role.getCode()));
        if (role.getId() == null) {
            if (r != null) {
                throw new BusinessException("角色编码已经被使用");
            }
            baseMapper.insert(role);
        } else {
            baseMapper.updateById(role);
        }
    }
}
